package com.alks.function.service.impl.quotation;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.alks.common.data.dto.SysUserTokenDTO;
import com.alks.common.data.thread.UserIdThread;
import com.alks.common.service.RedisService;
import com.alks.common.utils.DateUtils;
import com.alks.common.utils.ImageUtils;
import com.alks.common.utils.excelUtils.ExcelPoiUtils;
import com.alks.common.utils.excelUtils.ExcelUtils;
import com.alks.common.utils.stringUtils.ZStringUtils;
import com.alks.entity.data.entity.*;
import com.alks.entity.data.enums.ResultCodeEnum;
import com.alks.entity.data.response.ResponseInfo;
import com.alks.entity.exception.ServiceErrorException;
import com.alks.function.data.dto.QuotationDto;
import com.alks.function.data.dto.QuotationTypeDetailDto;
import com.alks.function.data.dto.QuotationTypeDto;
import com.alks.function.data.dto.StyleResearchDto;
import com.alks.function.data.request.quotation.*;
import com.alks.function.mapper.QuotationTypeDetailMapper;
import com.alks.function.mapper.QuotationTypesMapper;
import com.alks.function.mapper.chengKong.LargeCargoUsageMapper;
import com.alks.function.service.QuotationTypeService;
import com.alks.function.service.SysUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;

/**
 * @author:xxxxx
 * @create: 2023-06-17 10:03
 * @Description: 报价型体实现
 */
@Service
@Slf4j
public class QuotationTypeServiceImpl extends ServiceImpl<QuotationTypesMapper, QuotationType> implements QuotationTypeService {
    @Autowired
    SysUserService service;
    @Autowired
    RedisService redisService;
    @Autowired
    QuotationTypesMapper quotationTypesMapper;

    @Override
    public ResponseInfo quotationList(QuotationTypeRequest request) {
        if (request == null) {
            return ResponseInfo.error(ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getMessage(), ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getCode());
        }
        //获取用户id 将用户名放入
        if (request.getQuotation() != null && request.getQuotation() == 1) {
            SysUserTokenDTO user = UserIdThread.get();
            request.setLoginName(user.getUserName());
        }
        List<QuotationType> quotationList = quotationTypesMapper.quotationList(request);
        QuotationTypeDto dto = new QuotationTypeDto();
        dto.setList(quotationList);
        Long total = quotationTypesMapper.quotationTotal(request);
        dto.setTotal(total);
        return ResponseInfo.ok(dto);
    }

    @Override
    public ResponseInfo quotationListDetail(QuotationTypeDetailRequest request) {
        if (request == null) {
            return ResponseInfo.error(ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getMessage(), ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getCode());
        }
        if (request.getStyle() == null || request.getSlipNo() == null || "".equals(request.getStyle()) || "".equals(request.getSlipNo())) {
            return ResponseInfo.ok();
        }
        List<QuotationTypeDetail> quotationTypeDetails = quotationTypesMapper.quotationListDetail(request);
        QuotationTypeDetailDto quotationTypeDetailDto = new QuotationTypeDetailDto();
        quotationTypeDetailDto.setList(quotationTypeDetails);
        PageHelper.clearPage();
        // 当去当前明细价格
        BigDecimal totalPrice = quotationTypesMapper.getTotalPrice(request);
        if (totalPrice != null) {
            quotationTypeDetailDto.setTotalPrice(totalPrice.setScale(5, RoundingMode.HALF_UP));
        }
        //计算项目报价明细
        List<Map> argument = quotationTypesMapper.getArgument(request);
        quotationTypeDetailDto.setMaps(argument);
        List<String> rates = quotationTypesMapper.getYfStyleCostBase2();
        quotationTypeDetailDto.setRate(new BigDecimal(rates.get(0)));
        Long total = quotationTypeDetailMapper.getQuotationDetailTotal(request);
        quotationTypeDetailDto.setTotal(total);
        return ResponseInfo.ok(quotationTypeDetailDto);
    }

    @Override
    public ResponseInfo updateQuotationTypeDetail(IQuotationDetailRequest request) {
        if (request == null) {
            return ResponseInfo.error(ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getMessage(), ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getCode());
        }
        SysUserTokenDTO user = UserIdThread.get();
        request.setQuotationName(user.getLoginName());
        Integer integer = quotationTypesMapper.updateQuotationTypeDetail(request);
        if (integer == null || integer < 0) {
            //TODO 后面加
            return ResponseInfo.error(ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getMessage(), ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getCode());
        }
        return ResponseInfo.ok("", "修改成功");
    }

    @Override
    public ResponseInfo getYfStyleCostBase() {
        List<Map> base1 = quotationTypesMapper.getYfStyleCostBase1();
        HashMap<String, Object> map = new HashMap<>();
        map.put("报价项目明细", base1);
        List<String> base2 = quotationTypesMapper.getYfStyleCostBase2();
        map.put("汇率", base2);
        return ResponseInfo.ok(map);
    }

    @Override
    public ResponseInfo setYfStyleCostBase(Map<String, Object> map) {
        List<Map> base1 = (List<Map>) map.get("报价项目明细");
        quotationTypesMapper.updateYfStyleCostBase(base1);
        return null;
    }

    @Autowired
    QuotationTypeDetailMapper quotationTypeDetailMapper;

    // 插入材料报价
    @Override
    @Transactional
    public ResponseInfo setQuotationTypeDetail(IQuotationDetailRequest request) {
        if (request == null) {
            return ResponseInfo.error(ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getMessage(), ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getCode());
        }
        //先查询 看id是否存在 不存在添加 存在不添加
        if (StringUtils.isEmpty(request.getSeqNo())) {
            return ResponseInfo.error("序号不能为空", 405);
        }
        if (StringUtils.isEmpty(request.getStyle()) || StringUtils.isEmpty(request.getColor()) || StringUtils.isEmpty(request.getSlipNo())) {
            return ResponseInfo.error("型体颜色单号不能为空", 405);
        }
        QuotationTypeDetailRequest detailRequest = new QuotationTypeDetailRequest();
        BeanUtils.copyProperties(request, detailRequest);
        List<QuotationTypeDetail> list = quotationTypesMapper.quotationListDetail(detailRequest);
        List<String> collect = list.stream().map(QuotationTypeDetail::getSeqNo).collect(Collectors.toList());
        List<String> strings = collect.stream().filter(x -> Objects.equals(request.getSeqNo(), x)).collect(Collectors.toList());
        if (strings.size() != 0) {
            return ResponseInfo.error("序号已存在", 405);
        }
        //插入材料明细信息
        QuotationTypeDetail quotationTypeDetail = new QuotationTypeDetail();
        BeanUtils.copyProperties(request, quotationTypeDetail);
        SysUserTokenDTO dto = UserIdThread.get();
        quotationTypeDetail.setCompanyId(dto.getCompanyId());
        //获取当前报价人姓名
        quotationTypeDetail.setSysUser(request.getQuotationName());
        // 需要做计算计算出AMT
        if (quotationTypeDetail.getPrice() == null) {
            quotationTypeDetail.setPrice(new BigDecimal(0));
        }
        if (quotationTypeDetail.getCostUsage() == null) {
            quotationTypeDetail.setCostUsage(new BigDecimal("1.00"));
        }
        if (quotationTypeDetail.getJgPrice() == null) {
            quotationTypeDetail.setJgPrice(new BigDecimal("0"));
        }
        String mtlName = "";
        String mtlColor = "";
        if (quotationTypeDetail.getMtlColor() != null) {
            mtlName = quotationTypeDetail.getMtlName();
        }
        if (quotationTypeDetail.getMtlName() != null) {
            mtlColor = quotationTypeDetail.getMtlColor();
        }
        String mtlNo = quotationTypeDetailMapper.getMtlNo(mtlName, mtlColor);
        quotationTypeDetail.setMtlNo(mtlNo);
        BigDecimal add = quotationTypeDetail.getPrice().add(quotationTypeDetail.getJgPrice());
        BigDecimal amt = add.multiply(quotationTypeDetail.getCostUsage()).setScale(2, RoundingMode.HALF_UP);
        quotationTypeDetail.setAmt(amt);
        quotationTypeDetail.setCompanyId(UserIdThread.get().getCompanyId());
        quotationTypeDetailMapper.insert(quotationTypeDetail);
        //计算项目报价明细
        //查找USB的价格统计
        List<Map<String, BigDecimal>> totalAmtUSD = quotationTypeDetailMapper.getTotalAmtUSD(request);
        //查找RMB价格统计
        List<Map<String, BigDecimal>> totalAmtRMB = quotationTypeDetailMapper.getTotalAmtRMB(request);
        BigDecimal rate = quotationTypeDetailMapper.getRate();
        //修改格式为 “面部” ： price
//        if (totalAmtRMB.size() > 0 && totalAmtUSD.size() > 0){
//            List<Map<String,BigDecimal>> newTotalUsb =getAmtMap(totalAmtUSD);
//            List<Map<String,BigDecimal>> newTotalRmb = getAmtMap(totalAmtRMB);
//            extracted(rate, newTotalUsb, newTotalRmb);
//        }
        //TODO 暂不做处理
//        log.info(String.valueOf(newTotalUsb));
        return ResponseInfo.ok("添加成功");
    }

    @Override
    public ResponseInfo getMtlProperty() {
        return ResponseInfo.ok(quotationTypeDetailMapper.getMtlProperty());
    }

    @Override
    public ResponseInfo getCurrency() {
        return ResponseInfo.ok(quotationTypeDetailMapper.getCurrency());
    }

    @Override
    public ResponseInfo deleteQuotationTypeDetail(DeleteQuotationDetailRequest request) {
        if (request == null) {
            return ResponseInfo.error(ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getMessage(), ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getCode());
        }
        if (request.getStyle() == null || "".equals(request.getStyle())) {
            return ResponseInfo.error("型体不能为空", 503);
        }
        if (request.getSlipNo() == null || "".equals(request.getSlipNo())) {
            return ResponseInfo.error("slipNo不能为空", 503);
        }
        if (request.getSeqNos() == null || request.getSeqNos().isEmpty()) {
            return ResponseInfo.error("id不能为空", 503);
        }
        quotationTypeDetailMapper.deleteQuotationDetails(request);
        return ResponseInfo.ok("删除成功");
    }

    @Override
    @Transactional
    public ResponseInfo deleteQuotation(DeleteQuotationRequest request) {
        if (request == null) {
            return ResponseInfo.error(ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getMessage(), ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getCode());
        }
        if (request.getSlipNo() == null || request.getSlipNo().isEmpty()) {
            return ResponseInfo.error("slipid不能为空", 503);
        }
        if (request.getStyle() == null || request.getStyle().isEmpty()) {
            return ResponseInfo.error("型体不能为空", 503);
        }
        if (request.getStyle().size() == 1 && request.getSlipNo().size() == 1) {
            String slipNo = request.getSlipNo().get(0);
            String style = request.getStyle().get(0);
            Integer size = quotationTypeDetailMapper.selectListDetail(slipNo, style);
            if (size.intValue() != 0) {
                return ResponseInfo.error("删除失败，型体明细表不为空", 503);
            }
        }
        LambdaQueryWrapper<QuotationTypeDetail> wrapper = new LambdaQueryWrapper<>();
        List<String> styles = request.getStyle();
        List<String> slipNo = request.getSlipNo();
        wrapper.in(styles != null && styles.size() > 0, QuotationTypeDetail::getStyle, styles).
                in(slipNo != null && slipNo.size() > 0, QuotationTypeDetail::getSlipNo, slipNo);
        List<QuotationTypeDetail> quotationTypeDetails = quotationTypeDetailMapper.selectList(wrapper);
        if (quotationTypeDetails != null && quotationTypeDetails.size() > 0) {
            return ResponseInfo.error("删除失败，型体明细表不为空", 503);
        }
        for (int i = 0; i < styles.size(); i++) {
            String style = styles.get(i);
            String slip = slipNo.get(i);
            quotationTypesMapper.deleteByStyleSlipNo(style, slip);
        }
        return ResponseInfo.ok("删除成功");
    }

    @Override
    public ResponseInfo getQuotationCondition() {
        HashMap<String, List> map = new HashMap<>();
        List<String> customs = quotationTypesMapper.getQuotationCustoms();
        List<String> seasons = quotationTypesMapper.getQuotationSeasons();
        map.put("brands", customs);
        map.put("seasons", seasons);
        return ResponseInfo.ok(map);
    }

    @Override
    public ResponseInfo getQuotation(GetQuotationRequest request) {
        if (request == null) {
            return ResponseInfo.error(ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getMessage(), ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getCode());
        }
        if (request.getPageNum() == null || request.getPageSize() == null) {
            request.setPageNum(1);
            request.setPageSize(10);
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize(), false);
        QuotationDto dto = new QuotationDto();
        List<Quotation> quotations = quotationTypesMapper.getQuotations(request);
        dto.setList(quotations);
        Long total = quotationTypesMapper.getQuotationsTotal(request);
        dto.setTotal(total);
        return ResponseInfo.ok(dto);
    }

    // 获取整合为美元后的金额

    private void extracted(BigDecimal rate, List<Map<String, BigDecimal>> newTotalUsb, List<Map<String, BigDecimal>> newTotalRmb) {
        newTotalRmb.forEach(new Consumer<Map<String, BigDecimal>>() {
            @Override
            public void accept(Map<String, BigDecimal> stringBigDecimalMap) {
                Set<String> set = stringBigDecimalMap.keySet();
                set.forEach(new Consumer<String>() {
                    @Override
                    public void accept(String s) {
                        if ("".equals(s) || s == null) {
                            return;
                        }
                        if (stringBigDecimalMap.get(s) instanceof BigDecimal) {
                            BigDecimal rmb = stringBigDecimalMap.get(s);
                            List<Map<String, BigDecimal>> maps = newTotalUsb.stream().filter(x -> x.get(s) != null).collect(Collectors.toList());
                            if (maps.size() == 0) {
                                return;
                            }
                            BigDecimal usb = maps.get(0).get(s);
                            if (rmb != null) {
                                rmb = rmb.divide(rate, 5, BigDecimal.ROUND_HALF_UP);
                                if (usb != null) {
                                    BigDecimal finalUsb = usb.add(rmb);
                                    newTotalUsb.forEach(new Consumer<Map<String, BigDecimal>>() {
                                        @Override
                                        public void accept(Map<String, BigDecimal> stringBigDecimalMap) {
                                            boolean bool = stringBigDecimalMap.containsKey(s);
                                            if (bool) {
                                                stringBigDecimalMap.put(s, finalUsb);
                                            }
                                        }
                                    });
                                }
                            }
                        }
                    }
                });
            }
        });
    }

    // 转换map格式
    private List<Map<String, BigDecimal>> getAmtMap(List<Map<String, BigDecimal>> totalAmtRMB) {
        ArrayList<Map<String, BigDecimal>> list = new ArrayList<>();
        totalAmtRMB.forEach(new Consumer<Map<String, BigDecimal>>() {
            @Override
            public void accept(Map<String, BigDecimal> stringBigDecimalMap) {
                HashMap<String, BigDecimal> map = new HashMap<>();
                ArrayList<Object> arrayList = new ArrayList<>();
                if (stringBigDecimalMap == null || stringBigDecimalMap.keySet().size() < 2) {
                    return;
                }
                stringBigDecimalMap.keySet().forEach(new Consumer<String>() {
                    @Override
                    public void accept(String s) {
                        arrayList.add(stringBigDecimalMap.get(s));
                    }
                });
                map.put((String) arrayList.get(0), (BigDecimal) arrayList.get(1));
                list.add(map);
            }
        });
        return list;
    }

    //取型体
    @Override
    @Transactional
    public ResponseInfo quotationSetHeadAndDetail(QuotationRequest request) {
        if (request == null) {
            return ResponseInfo.error(ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getMessage(), ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getCode());
        }
        List<Quotation> list = request.getQuotations();
        if (list.size() == 0) {
            return ResponseInfo.error(ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getMessage(), ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getCode());
        }
        SysUserTokenDTO sysUser = UserIdThread.get();
        //先将数据放入 head表中
        int b = 0;
        for (Quotation quotation : list) {
//            quotationTypesMapper.setCfg(quotation);
            b++;
            QuotationType quotationType = new QuotationType();
            Date date = new Date();
            String slipNo = "BF00000";
            String s = new SimpleDateFormat("ss").format(date);
            slipNo += s;
            slipNo += b;
            quotationType.setStyle(quotation.getStyleNo());
            quotationType.setColor(quotation.getStyleColor());
            quotationType.setCompanyId(UserIdThread.get().getCompanyId());
            quotationType.setStyleName(quotation.getStyleName());
            quotationType.setCustStyle(quotation.getCustStyle());
            quotationType.setCustom(quotation.getCustNo());
            quotationType.setSeason(quotation.getSeason());
            quotationType.setSolePart(quotation.getSolePart());
            quotationType.setSysUser(sysUser.getUserName());
            quotationType.setCutTool(quotation.getCutTool());
            quotationType.setSysDate(new Date());
            quotationType.setSizeRegion("-");
            quotationType.setLastMold(quotation.getLastMode());
            quotationType.setSlipNo(slipNo);
            quotationType.setStylePhoto(quotation.getStylePhoto());
            quotationTypesMapper.save(quotationType, quotation.getMidSize(), quotation.getBaseSize());
            writeInQuotationDetail(quotation.getStyleNo(), quotation.getStyleColor(), quotationType.getSlipNo());
            //将取型体设置为y
            List<String> attach = quotationTypeDetailMapper.getAttach();
            setAttach(attach, sysUser.getUserName(), quotationType.getSlipNo(), quotationType.getStyle(), quotationType.getColor());
        }
        return ResponseInfo.ok("添加成功");
    }

    //写入 yf_style_cost
    @Autowired
    LargeCargoUsageMapper mapper;

    private void writeInQuotationDetail(String styleNo, String styleColor, String slipNo) {
        SysUserTokenDTO sysUser = UserIdThread.get();
        Integer num = quotationTypesMapper.getByYfBomHead(styleNo, styleColor);
        if (num <= 0) {
            throw new ServiceErrorException("存在未建档的型体配色");
        }
        List<QuotationMaster> quotations = quotationTypeDetailMapper.getInQuotationBom(styleNo, styleColor);
        if (ZStringUtils.isEmpty(quotations)) {
            return;
        }
        List<QuotationMaster> newList = new ArrayList<>();
        newList.addAll(quotations);
        for (QuotationMaster quotation : quotations) {
            quotation.setSysUser(sysUser.getUserName());
            quotation.setSysDate(new Date());
            List<YfBomFitSub> fitSubs = mapper.getYfBomFitSub(quotation.getMtlNo());
            if (!ZStringUtils.isEmpty(fitSubs)) {
                BigDecimal ziSeq = quotation.getSeqNo();
                for (YfBomFitSub fitSub : fitSubs) {
                    QuotationMaster master = new QuotationMaster();
                    BeanUtils.copyProperties(quotation, master);
                    ziSeq = ziSeq.add(new BigDecimal("0.1"));
                    master.setSeqNo(new BigDecimal(ziSeq.toString()));
                    master.setMtlType("子项");
                    master.setMtlName(fitSub.getSubMtlName());
                    master.setMtlNo(fitSub.getSubMtlNo());
                    master.setMtlSpec(fitSub.getSubMtlSpec());
                    master.setMtlUnit(fitSub.getSubMtlUnit());
                    master.setVendor(fitSub.getVendor());
                    newList.add(master);
                }
            }
            //如果该部位材料是合贴的话将子项写入查询子项

        }
        quotationTypeDetailMapper.insertList(newList, slipNo);
    }

    //添加到attach表中 amt不设置
    public void setAttach(List<String> attach, String sysUser, String slipNo, String style, String color) {
        BigDecimal seqNo = new BigDecimal(0);
        ArrayList<Map> maps = new ArrayList<>();
        for (String att : attach) {
            HashMap<String, Object> map = new HashMap<>();
            seqNo = seqNo.add(new BigDecimal(1));
            map.put("sysUser", sysUser);
            map.put("slipNo", slipNo);
            map.put("att", att);
            map.put("style", style);
            map.put("color", color);
            map.put("seqNo", seqNo);
            map.put("companyId",UserIdThread.get().getCompanyId());
            maps.add(map);
        }
        quotationTypeDetailMapper.insertAttach(maps);
    }

    @Override
    public ResponseInfo reAndDevelopList(ReAndDevelopRequest request) {
        if (request == null) {
            return ResponseInfo.error(ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getMessage(), ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getCode());
        }
        List<BomStyle> list = quotationTypesMapper.getBomStyleList(request);
        HashSet<String> sets = new HashSet<>();
        list.forEach(x -> sets.add(x.getStyle()));
        HashMap<String, List<BomStyle>> map = new HashMap<>();
        sets.forEach(x -> map.put(x, list.stream().filter(y -> y.getStyle().equals(x)).collect(Collectors.toList())));
        return ResponseInfo.ok(map);
    }

    @Override
    public ResponseInfo getReAndDevelopCondition() {
        HashMap<String, List> map = new HashMap<>();
        List<ReAndDevelopCondition> list = quotationTypesMapper.getReAndDevelopCondition();
        map.put("list", list);
        return ResponseInfo.ok(map);
    }

    @Override
    public ResponseInfo getBomStyleMaterial(ReAndDevelopRequest request) {
        if (request == null) {
            return ResponseInfo.error(ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getMessage(), ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getCode());
        }
        List<BomStyleMaterial> list = quotationTypesMapper.getBomStyleMaterial(request);
        for (BomStyleMaterial detail : list) {
            if (detail.getSegment() != null) {
                detail.setSegment(detail.getSegment().setScale(6, RoundingMode.HALF_UP));
            }
            if (detail.getUsage() != null) {
                detail.setUsage(detail.getUsage().setScale(6, RoundingMode.HALF_UP));
            }
        }
        return ResponseInfo.ok(list);
    }

    @Override
    public ResponseInfo bomStyleDetail(String mtlNo) {
        if (mtlNo == null) {
            return ResponseInfo.error(ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getMessage(), ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getCode());
        }
        List<BomStyleDetail> list = quotationTypesMapper.bomStyleDetail(mtlNo);
        return ResponseInfo.ok(list);
    }

    @Override
    public ResponseInfo setBomStyleRemark(String style, String color, String remark) {
        Integer no = quotationTypesMapper.setBomStyleRemark(style, color, remark);
        return ResponseInfo.ok();
    }

    @Override
    public ResponseInfo getStyleResearchCondition() {
        HashMap<String, List> map = new HashMap<>();
        List<String> techPerson = quotationTypesMapper.getResearchTechPerson();
        List<String> seasons = quotationTypesMapper.getResearchSeason();
        List<String> customStyles = quotationTypesMapper.getResearchCustNo();
        map.put("seasons", seasons);
        map.put("techPerson", techPerson);
        map.put("customStyles", customStyles);
        return ResponseInfo.ok(map);
    }

    //研发型体查询
    @Override
    public ResponseInfo getStyleResearch(StyleResearchRequest request) {
        if (request == null) {
            return ResponseInfo.error(ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getMessage(), ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getCode());
        }
        if (request.getPageNum() == null || request.getPageSize() == null) {
            request.setPageNum(1);
            request.setPageSize(10);
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize(), false);
        StyleResearchDto dto = new StyleResearchDto();
        List<StyleResearch> list = quotationTypesMapper.getStyleResearch(request);
        dto.setList(list);
        Long total = quotationTypesMapper.getStyleResearchTotal(request);
        dto.setTotal(total);
        return ResponseInfo.ok(dto);
    }

    @Override
    public ResponseInfo getStyleResearchDetail(String styleNo) {
        if (styleNo == null) {
            return ResponseInfo.error(ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getMessage(), ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getCode());
        }
        Map<String, List> map = new HashMap<>();
        //型体配色
        List<StyleResearchColorDetail> styleColor = quotationTypesMapper.getStyleResearchColorDetail(styleNo);
        //编码资料
        List<StyleResearchCodeDetail> styleCode = quotationTypesMapper.getStyleResearchCodeDetail(styleNo);
        //制具资料
        List<StyleResearchToolsDetail> styleTools = quotationTypesMapper.getStyleResearchToolsDetail(styleNo);
        map.put("styleColor", styleColor);
        map.put("styleCode", styleCode);
        map.put("styleTools", styleTools);
        return ResponseInfo.ok(map);
    }

    @Override
    public ResponseInfo quotationCondition() {
        Map<String, List> map = new HashMap<>();
        List<String> brands = quotationTypesMapper.getQuotationBrands();
        List<String> seasons = quotationTypesMapper.getQuotationConditionSeasons();
        map.put("brands", brands);
        map.put("seasons", seasons);
        return ResponseInfo.ok(map);
    }

    @Override
    public ResponseInfo getPcStyleCraftHead(PcStyleCraftRequest request) {
        if (request == null) {
            return ResponseInfo.error(ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getMessage(), ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getCode());
        }
        if (request.getPageNum() == null || request.getPageSize() == null) {
            request.setPageNum(1);
            request.setPageSize(10);
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize(), false);
        HashMap<String, Object> map = new HashMap<>();
        List<PcStyleCraftRep> list = quotationTypesMapper.getPcStyleCraftHead(request);
        Long total = quotationTypesMapper.getPcStyleCraftHeadTotal(request);
        map.put("list", list);
        map.put("total", total);
        return ResponseInfo.ok(map);
    }

    @Override
    public ResponseInfo getPcStyleCraftDetail(String style, String color, String flag) {
        HashMap<String, List<PcStyleProcessCraftRep>> map = new HashMap<>();
        List<PcStyleProcessCraftRep> list = quotationTypesMapper.getPcStyleCraftDetail(style, color, flag);
        map.put("list", list);
        return ResponseInfo.ok(map);
    }

    @Override
    public ResponseInfo getPcBomStyleColor(PcBomColorRequest request) {
        if (request == null) {
            return ResponseInfo.error(ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getMessage(), ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getCode());
        }
        if (request.getPageNum() == null || request.getPageSize() == null) {
            request.setPageNum(1);
            request.setPageSize(10);
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize(), false);
        HashMap<String, Object> map = new HashMap<>();
        List<PcBomMaterialColorDetailRep> list = quotationTypesMapper.getPcBomStyleColor(request);
        Long total = quotationTypesMapper.getPcBomStyleColorTotal(request);
        map.put("list", list);
        map.put("total", total);
        return ResponseInfo.ok(map);
    }

    @Override
    public ResponseInfo getPcBomStyleDetail(String mtlNo) {
        HashMap<String, List<PcBomStyleColorDetailRep>> map = new HashMap<>();
        List<PcBomStyleColorDetailRep> list = quotationTypesMapper.getPcBomStyleDetail(mtlNo);
        map.put("list", list);
        return ResponseInfo.ok(map);
    }

    @Transactional
    @Override
    public ResponseInfo updateQuotationStyleCheck(QuotationTypeCheckRequest request) {
        if (request == null) {
            return ResponseInfo.error(ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getMessage(), ResultCodeEnum.LOGIN_CONFIG_IS_NULL.getCode());
        }
        quotationTypesMapper.updateQuotationCheck(request);
        return ResponseInfo.ok("修改成功");
    }

    @Override
    public ResponseInfo updateUsdAndTypeName(UpdateQuotationRsbAndTypeRequest request) {
        quotationTypesMapper.updateUsdAndTypeName(request);
        return ResponseInfo.ok("更新成功");
    }

    @Override
    public void downloadReDevelop(HttpServletResponse response, ReAndDevelopRequest req) {
        Map<String, Object> map = quotationTypesMapper.getDetailForStyle(req);
        String path = (String) map.get("photoPath");
        byte[] image = null;
        if (path != null && !path.isEmpty()) {
            image = ImageUtils.readAndResizeImage(path, 200, 180);
        }
        List<BomStyleMaterial> list = quotationTypesMapper.getBomStyleMaterial(req);
        if (ObjectUtils.isEmpty(map) || ObjectUtils.isEmpty(list)) {
            throw new ServiceErrorException("查询数据为空，不可导出！");
        }
        map.put("list", list);
        ExcelPoiUtils.writeExcelWithPictureToResponse(response, "templates/研发用量模板导出.xls", map, image, 24, 27, 1, 4);
    }

    @Override
    public void downloadStyle(HttpServletResponse response, List<String> list) throws UnsupportedEncodingException {
        Map<String, Object> map = new HashMap<>();
        List<Map<String, Object>> lists = quotationTypesMapper.getStyleExcel(list);
        map.put("list", lists);
        ExcelPoiUtils.writeExcelList(response, map, "templates/研发型体模板.xls");
    }

    @Override
    public void downloadPcBom(HttpServletResponse response, PcBomColorRequest request) {
        Map<Integer, List<Map<String, Object>>> mapList = new HashMap<>();
        List<PcBomMaterialColorDetailRep> list = quotationTypesMapper.getPcBomStyleColor(request);
        if (ObjectUtils.isEmpty(list)) {
            throw new ServiceErrorException("查询数据为空，不可导出！");
        }
        int pageSize = 60000;
        List<List<PcBomMaterialColorDetailRep>> lists = splitList(list, pageSize);
        int sheetIndex = 1;
        for (List<PcBomMaterialColorDetailRep> t : lists) {
            List<Map<String, Object>> exportList = new ArrayList<>();
            Map<String, Object> sheetData = new HashMap<>();
            sheetData.put("sheetName", "sheet"+sheetIndex);
            sheetData.put("list", t);
            exportList.add(sheetData);
            mapList.put(sheetIndex, exportList);
            sheetIndex++;
        }
        String fileName ="型体BOM导出"+"_" + DateUtils.dateTimeNow() + ".xls";
        try {
            TemplateExportParams templateParams = new TemplateExportParams("templates/型体配色材料模板.xls", true);
            ExcelUtils.setResponseZF(response, fileName);
            Workbook workbook = ExcelExportUtil.exportExcelClone(mapList,templateParams);
            workbook.write(response.getOutputStream());
            workbook.close();
        } catch (Exception e) {
            log.error("型体BOM导出失败, 错误信息: {}", e.getMessage());
            throw new ServiceErrorException("型体BOM导出失败!");
        }
    }

    /**
     * 拆分列表
     * @param sourceList
     * @param pageSize
     * @return
     * @param <T>
     */
    public static <T> List<List<T>> splitList(List<T> sourceList, int pageSize) {
        List<List<T>> result = new ArrayList<>();
        int totalSize = sourceList.size();
        int pageCount = (totalSize + pageSize - 1) / pageSize;

        for (int i = 0; i < pageCount; i++) {
            int start = i * pageSize;
            int end = Math.min(start + pageSize, totalSize);
            result.add(sourceList.subList(start, end));
        }
        return result;
    }

    @Override
    public ResponseInfo gouXQuotation(Quotation quotation) {
        Integer num = quotationTypesMapper.getByYfBomHead(quotation.getStyleNo(), quotation.getStyleColor());
        if (num <= 0) {
            throw new ServiceErrorException("存在未建档的型体配色");
        }
        return ResponseInfo.ok();
    }
}
